package home

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"minititok/Entities"
	"minititok/Services"
	"net/http"
	"strconv"
)

func giveFavorites(c *gin.Context) {
	type Responsebody struct {
		Isfavorites bool   `json:"isfavorites"`
		Av          string `json:"av"`
	}
	var body Responsebody
	if err := c.ShouldBindJSON(&body); err != nil {
		_ = c.Error(fmt.Errorf("请求格式错误:" + err.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": "请求错误"})
		return
	}
	av := body.Av
	av = av[2:]
	user, _ := c.Get("user")
	currUser, _ := user.(*Entities.User)
	Fav, err := Services.FindFavoritesByAvAndUsername(av, currUser.Username)
	if err != nil {
		_ = c.Error(fmt.Errorf("数据库错误,找不到收藏记录:" + err.Error()))
		c.JSON(http.StatusUnauthorized, gin.H{"customMessage": "记录错误"})
		return
	}
	errUpdata := Services.UpdateFavorite(Fav, body.Isfavorites)
	if errUpdata != nil {
		_ = c.Error(fmt.Errorf("数据库错误,无法更新状态:%w", err))
		c.JSON(http.StatusUnauthorized, gin.H{"customMessage": "数据插入失败"})
		return
	}
	intAv, _ := strconv.Atoi(av)
	currVideo, _ := Services.FindVideoByAV(int64(intAv))
	countErr := Services.CountFavorites(currVideo)
	if countErr != nil {
		_ = c.Error(fmt.Errorf("数据库错误,计数失败:%w", err))
		log.Println(countErr)
	}
	c.JSON(http.StatusOK, gin.H{"customMessage": "success"})
}
